package com.ykqx.weather.app.util;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Created with IntelliJ IDEA.
 * User: Legolas
 * Date: 2017/6/21 0021
 */
public class ServletResponseUtil {

    public static String FileResponse(File file, HttpServletResponse response) throws IOException{
        FileInputStream fis = new FileInputStream(file);
        FileChannel fc = fis.getChannel();
        int bufferSize = 5 * 1024;
        ByteBuffer bb = ByteBuffer.allocateDirect(6 * bufferSize);
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] buffer = new byte[bufferSize];
        int len, nGet;
        try {

            while ((len = fc.read(bb)) != -1) {
                if (len == 0)
                    continue;
                bb.position(0);
                bb.limit(len);
                while (bb.hasRemaining()) {
                    //bb中剩下的数据与buffer大小比较，若剩余数据小，一次性放到buffer中，若比buffer大，则读buffer大小
                    nGet = Math.min(bb.remaining(), bufferSize);
                    // transfer bytes from this buffer into the given destination array
                    bb.get(buffer, 0, nGet);
                    // write bytes to output
                    outputStream.write(buffer);
                }
                bb.clear();
            }
            return "success";

        } catch (IOException e) {
            e.printStackTrace();
            return "failed";

        } finally {
            bb.clear();
            fc.close();
            fis.close();
        }
    }



     /*
   //jcifs
    public static String SmbFileResponse(SmbFile file, HttpServletResponse response) {
        try {
            SmbFileInputStream fis = new SmbFileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(fis);
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] buf = new byte[100 * 1024];
            int len;
            while ((len = bis.read(buf)) != -1) {
                outputStream.write(buf, 0, len);
                outputStream.flush();

            }
            fis.close();
            bis.close();
            outputStream.close();
            return null;

        } catch (IOException e) {
            e.printStackTrace();
            return "failed";

        }
    }*/
}
